import sys
from types import SimpleNamespace

import pygame

from common import (add_score, black, blue, font_path, get_score,
                    go_next_level, green, pink, red, white, yellow)

from .chinese_input import TextInput

################################
# Constants
################################
screen_width, screen_height = 1200, 700
pygame.display.set_caption("按钮示例")

# 设置字体
font = pygame.font.Font(font_path, 15)

button_text_font = pygame.font.Font(font_path, 20)
small_button_text_font = pygame.font.Font(font_path, 8)

questions = [
    "问题1：启动电路动作规律",
    "问题2：SJ↑是什么意思",
    "问题3：CAJ前接点和条件电源作用",
    "问题4：道岔尖轨被阻转辙机状态",
    "问题5：为什么2DQJ保持原来状态",
    "问题6：若二极管Z被短路会发生什么",
    "问题7：电容C被击穿的后果",
    "问题8：分级控制第一级",
    "问题9：分级控制第二级",
    "问题10：分级控制第三级",
]
answers = [
    "有车不能动、锁闭不能动、不动就不动、一转转到底、遇阻往回转、转完断电源",
    "进路无车占用并未锁闭",
    "反映道岔单独操纵的手续",
    "电机空转1DQJ保持吸起切断表示电路",
    "2DQJ为极性保持继电器",
    "半波整流失去作用FBJ只有交流电不会吸起",
    "DBJ被短路",
    "1DQJ检查联锁条件",
    "2DQJ控制电机旋转方向",
    "直流电动机转换道岔",
]
user_answers = [""] * len(questions)

# 5x2, button width 200, height 40, margin 10
button_ca = SimpleNamespace(
    label="CA",
    rect=pygame.Rect(10, 10, 100, 40),
    color=pink,
    text="CA",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_zda = SimpleNamespace(
    label="ZDA",
    rect=pygame.Rect(120, 10, 100, 40),
    color=green,
    text="ZDA",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_zfa = SimpleNamespace(
    label="ZFA",
    rect=pygame.Rect(230, 10, 100, 40),
    color=blue,
    text="ZFA",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_dca = SimpleNamespace(
    label="DCA",
    rect=pygame.Rect(340, 10, 100, 40),
    color=blue,
    text="DCA",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)

button_fca = SimpleNamespace(
    label="FCA",
    rect=pygame.Rect(450, 10, 100, 40),
    color=yellow,
    text="FCA",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_1dqj_on = SimpleNamespace(
    label="1DQJ_ON",
    rect=pygame.Rect(10, 60, 100, 40),
    color=yellow,
    text="1DQJ励磁",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_2dqj = SimpleNamespace(
    label="2DQJ",
    rect=pygame.Rect(120, 60, 100, 40),
    color=yellow,
    text="2DQJ转极",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_1dqj_off = SimpleNamespace(
    label="1DQJ_OFF",
    rect=pygame.Rect(230, 60, 100, 40),
    color=yellow,
    text="1DQJ自闭",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_dbj = SimpleNamespace(
    label="DBJ",
    rect=pygame.Rect(340, 60, 100, 40),
    color=yellow,
    text="DBJ励磁",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_fbj = SimpleNamespace(
    label="FBJ",
    rect=pygame.Rect(450, 60, 100, 40),
    color=yellow,
    text="FBJ励磁",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
button_submit = SimpleNamespace(
    label="SUBMIT",
    rect=pygame.Rect(580, 10, 100, 40),
    color=yellow,
    text="提交",
    font_color=black,
    font=button_text_font,
    selected=False,
    enabled=False,
)
buttons = [
    button_ca,
    button_zda,
    button_zfa,
    button_dca,
    button_fca,
    button_1dqj_on,
    button_2dqj,
    button_1dqj_off,
    button_dbj,
    button_fbj,
]

images = []
for i in range(22):
    image = pygame.image.load(f"./assets/game_4/wps_doc_{i}.png")
    image = pygame.transform.scale(image, (1200, 600))
    images.append(image)


input_box = pygame.Rect(580, 60, 600, 30)
text_rect = pygame.Rect(700, 20, 1000, 40)

"""
点击CA，将图切换为图0 →  ZFA，切图1出问题1  1DQJ励磁，切图2出问题2→ 2DQJ转极，切图3出问题3 → 1DQJ自闭，切图4出问题4   FBJ励磁，切图5出问题5
点击CA，将图切换为图0→  ZDA，切图6出问题6  1DQJ励磁，切图7出问题7→ 2DQJ转极，切图8出问题8 → 1DQJ自闭，切图9出问题9   DBJ励磁，切图10出问题10
"""
path1 = {
    "image": images[0],
    "question": "点击ZFA或者ZDA切出问题",
    "answer": None,
    "children": {
        "ZFA": {
            "image": images[1],
            "question": questions[0],
            "answer": answers[0],
            "children": {
                "1DQJ_ON": {
                    "image": images[2],
                    "question": questions[1],
                    "answer": answers[1],
                    "children": {
                        "2DQJ": {
                            "image": images[3],
                            "question": questions[2],
                            "answer": answers[2],
                            "children": {
                                "1DQJ_OFF": {
                                    "image": images[4],
                                    "question": questions[3],
                                    "answer": answers[3],
                                    "children": {
                                        "FBJ": {
                                            "image": images[5],
                                            "question": questions[4],
                                            "answer": answers[4],
                                            "children": {},
                                        }
                                    },
                                }
                            },
                        }
                    },
                },
            },
        },
        "ZDA": {
            "image": images[6],
            "question": questions[5],
            "answer": answers[5],
            "children": {
                "1DQJ_ON": {
                    "image": images[7],
                    "question": questions[6],
                    "answer": answers[6],
                    "children": {
                        "2DQJ": {
                            "image": images[8],
                            "question": questions[7],
                            "answer": answers[7],
                            "children": {
                                "1DQJ_OFF": {
                                    "image": images[9],
                                    "question": questions[8],
                                    "answer": answers[8],
                                    "children": {
                                        "DBJ": {
                                            "image": images[10],
                                            "question": questions[9],
                                            "answer": answers[9],
                                            "children": {},
                                        }
                                    },
                                }
                            },
                        }
                    },
                },
            },
        },
    },
}


"""
点击FCA,切图11出问题1  1DQJ励磁，切图12出问题2 →2DQJ转极，切图13出问题3 →1DQJ自闭，切图14出问题4 →FBJ励磁，切图15出问题5
"""
path2 = {
    "image": images[11],
    "question": questions[0],
    "answer": answers[0],
    "children": {
        "1DQJ_ON": {
            "image": images[12],
            "question": questions[1],
            "answer": answers[1],
            "children": {
                "2DQJ": {
                    "image": images[13],
                    "question": questions[2],
                    "answer": answers[2],
                    "children": {
                        "1DQJ_OFF": {
                            "image": images[14],
                            "question": questions[3],
                            "answer": answers[3],
                            "children": {
                                "FBJ": {
                                    "image": images[15],
                                    "question": questions[4],
                                    "answer": answers[4],
                                    "children": {},
                                }
                            },
                        }
                    },
                }
            },
        }
    },
}

"""
点击DCA,切图16出问题6→  1DQJ励磁，切图17出问题7→  2DQJ转极，切图18出问题8→  1DQJ自闭，切图19出问题9 → DBJ励磁，切图20出问题10
"""
path3 = {
    "image": images[16],
    "question": questions[5],
    "answer": answers[5],
    "children": {
        "1DQJ_ON": {
            "image": images[17],
            "question": questions[6],
            "answer": answers[6],
            "children": {
                "2DQJ": {
                    "image": images[18],
                    "question": questions[7],
                    "answer": answers[7],
                    "children": {
                        "1DQJ_OFF": {
                            "image": images[19],
                            "question": questions[8],
                            "answer": answers[8],
                            "children": {
                                "DBJ": {
                                    "image": images[20],
                                    "question": questions[9],
                                    "answer": answers[9],
                                    "children": {},
                                }
                            },
                        }
                    },
                }
            },
        }
    },
}
path = {
    "CA": path1,
    "FCA": path2,
    "DCA": path3,
}
##############################################
# Global Variables
##############################################

# 输入框变量
cur_question = "Tips: 大字符表示按钮可以点击"
cur_answer = ""
user_text = ""
inputable = False
cursor_visible = True  # 光标是否可见
cursor_time = 0  # 计时光标闪烁
text_input = TextInput(
    prompt="> ",
    pos=input_box.topleft,
    screen_dimensions=(screen_width, screen_height),
    print_event=False,
    text_color="black",
)


cur_image = images[-1]
cur_path = path


def draw_buttons(screen):
    for button in buttons + [button_submit]:
        if button.selected:
            text = button.text + "(已选)"
        else:
            text = button.text
        if button.enabled:
            font = button_text_font
        else:
            font = small_button_text_font
        pygame.draw.rect(screen, button.color, button.rect)
        text = font.render(text, True, button.font_color)
        text_rect = text.get_rect(center=button.rect.center)
        screen.blit(text, text_rect)


def draw_text(screen):
    global user_text, cursor_visible
    text = font.render(cur_question, True, black)
    screen.blit(text, text_rect)

    # 绘制输入框
    pygame.draw.rect(screen, black, input_box, 2)

    # 绘制当前得分
    score = get_score()
    score_text = font.render(f"得分：{score}", True, red)

    # 渲染文本
    txt_surface = font.render(user_text, True, black)
    screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))

    screen.blit(score_text, (1100, 10))


def draw_image(screen):
    # 绘制图片
    if cur_image:
        screen.blit(cur_image, (0, 100))


def reset_button():
    for button in buttons + [button_submit]:
        button.selected = False
        button.enabled = False


def draw(screen):

    global user_text, cur_image, cursor_visible, cursor_time, cur_path, cur_question, cur_answer, inputable
    if not cur_path and not path:
        go_next_level()
    if not cur_path:
        reset_button()
        cur_path = path
    for button in buttons:
        button.enabled = button.label in cur_path

    if user_text:
        button_submit.enabled = True
    else:
        button_submit.enabled = False

    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.MOUSEBUTTONUP:
            # 如果用户点击输入框，激活输入框
            if input_box.collidepoint(event.pos) and inputable:
                text_input.activate()
            else:
                text_input.deactivate()
            for button in buttons:
                if button.rect.collidepoint(event.pos) and button.enabled:
                    button.selected = 1

                    if button.label in cur_path:
                        if len(cur_path[button.label]["children"]) > 1:
                            tmp = cur_path.get(button.label)
                        else:
                            tmp = cur_path.pop(button.label)
                        cur_question = tmp["question"]
                        cur_answer = tmp["answer"]
                        cur_image = tmp["image"]
                        user_text = ""
                        text_input.clear()
                        cur_path = tmp["children"]
                        button.enabled = True
                        if cur_answer:
                            inputable = True

            if button_submit.rect.collidepoint(event.pos):
                # print(text_input.get_text())
                if cur_answer and text_input.get_text() == cur_answer:
                    add_score(10)
                    user_text = "回答正确: +10分"
                else:
                    user_text = "正确答案：" + cur_answer
                inputable = False
                button_submit.selected = 1
                button_submit.enabled = False

    text_input.update(events)
    # 填充背景色
    screen.fill(white)

    # 绘制按钮
    draw_buttons(screen)

    # 绘制文本和输入框
    draw_text(screen)
    if inputable:
        text_input.draw(screen)

    # 绘制游戏图片
    draw_image(screen)

    # 更新显示
    pygame.display.flip()

    # 控制帧率
    pygame.time.Clock().tick(60)
